#coding=utf-8
__author__ = 'rsg'

import json


class Person(object):

    def __init__(self, name, sex, age):
        self.name = name
        self.sex = sex
        self.age = age

    def __str__(self):
        return 'name={0},sex={1},age={2}'.format(self.name, self.sex, self.age)

class PersonJsonEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Person):
            return {u'name': o.name, u'sex': o.sex, u'age': o.age}
        return json.JSONEncoder.default(self, o)


def my_object_hook(o):
    if isinstance(o, dict):
        p = Person(name=None, sex=None, age=None)
        p.name = o[u'name']
        p.sex = o[u'sex']
        p.age = o[u'age']
        return p
    return



p1 = Person(u'xiaom', u'm', 18)

data = json.dumps(p1, cls=PersonJsonEncoder)

print data
print type(data)

p2 = json.loads(data, object_hook=my_object_hook)
print p2
print type(p2)